﻿using System.Xml;
using AgCIM.Tools.IO.Shape;
using AgCIM.Tools.Maths.Numerics;
using NetTopologySuite.Utilities;
using Newtonsoft.Json;

namespace AgCIMProductFuncLib
{
    /// <summary>
    /// Shapefile线数据处理器 - 读取文件夹下所有*Line.shp文件并导出JSON
    /// </summary>
    public class LineShapefileProcessor
    {
        public BoundingBox GlobalBoundingBox;
        public List<ProductLine> products;
        public AgCIMProducts agCIMProducts = new AgCIMProducts();

        private string m_outputJsonDir;
        

        public void Load(string folderPath,string outputJsonDir)
        {
            products=new List<ProductLine>();
            agCIMProducts=new AgCIMProducts();

            m_outputJsonDir = outputJsonDir;

            ProcessLineShapefiles(folderPath);

            ProcessPointShapefiles(folderPath);

            ProcessProductShapefiles(folderPath);

            Export();
        }

        /// <summary>
        /// 读取文件夹下所有*Line.shp文件并导出JSON
        /// </summary>
        /// <param name="folderPath">文件夹路径</param>
        /// <param name="outputJsonPath">输出JSON文件路径</param>
        public void ProcessLineShapefiles(string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                throw new DirectoryNotFoundException($"文件夹不存在：{folderPath}");
            }
            GlobalBoundingBox=new BoundingBox();
            // 获取所有*Line.shp文件
            var lineShapefiles = Directory.GetFiles(folderPath, "*Line.shp", SearchOption.AllDirectories);
            if (lineShapefiles.Length == 0)
            {
                throw new FileNotFoundException($"未找到*Line.shp文件：{folderPath}");
            }

            foreach (var shpFilePath in lineShapefiles)
            {
                var product = new ProductLine()
                {
                    ProductName = Path.GetFileNameWithoutExtension(shpFilePath),
                    Lines = new List<LineFeature>()
                };
                products.Add(product);
                try
                {
                    // 读取Shapefile文件
                    var sr = new ShapeDataGetterField(shpFilePath);

                    // 遍历每个要素（线）
                    foreach (var feature in sr.AllRecords)
                    {
                        if (feature.PolyLine == null) continue;
                        var lineFeature = new LineFeature
                        {
                            Parts = new List<List<Coordinate>>(),
                            Attributes = new Dictionary<string, object>()
                        };
                        GlobalBoundingBox.Update(new BoundingBox
                        {
                            MinX = feature.PolyLine.BoundingBox.MinX,
                            MinY = feature.PolyLine.BoundingBox.MinY,
                            MaxX = feature.PolyLine.BoundingBox.MaxX,
                            MaxY = feature.PolyLine.BoundingBox.MaxY
                        });

                        // 处理多线段（一个要素可能包含多个子线段）
                        var geometry = feature.PolyLine;
                        if (geometry != null)
                        {
                            foreach (var part in geometry.Points)
                            {
                                var partCoordinates = new List<Coordinate>();
                                foreach (var point in part)
                                {
                                    partCoordinates.Add(new Coordinate
                                    {
                                        X = point.X,
                                        Y = point.Y
                                    });
                                }
                                lineFeature.Parts.Add(partCoordinates);
                            }
                        }

                        // 读取属性数据
                        foreach (var field in sr.Columns)
                        {
                            var value = feature.m_Attribute[field.FieldName];
                            lineFeature.Attributes.Add(field.FieldName, value.ToString());
                        }

                        product.Lines.Add(lineFeature);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"读取文件失败：{shpFilePath}，错误：{ex.Message}");
                }
            }

            
        }

        public void ProcessPointShapefiles(string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                throw new DirectoryNotFoundException($"文件夹不存在：{folderPath}");
            }
            // 获取所有*Line.shp文件
            var lineShapefiles = Directory.GetFiles(folderPath, "*Point.shp", SearchOption.AllDirectories);
            if (lineShapefiles.Length == 0)
            {
                throw new FileNotFoundException($"未找到*Point.shp文件：{folderPath}");
            }

            foreach (var shpFilePath in lineShapefiles)
            {
                var product = new ProductLine()
                {
                    ProductName = Path.GetFileNameWithoutExtension(shpFilePath),
                    PointLayer = new List<PointFeature>()
                };
                products.Add(product);
                try
                {
                    // 读取Shapefile文件
                    var sr = new ShapeDataGetterField(shpFilePath);

                    // 遍历每个要素（线）
                    foreach (var feature in sr.AllRecords)
                    {
                        if (feature.Point == null) continue;
                        var lineFeature = new PointFeature
                        {
                            Point=new Coordinate() {  X=feature.Point.X, Y=feature.Point.Y },
                            Attributes = new Dictionary<string, object>()
                        };
                       
                        // 读取属性数据
                        foreach (var field in sr.Columns)
                        {
                            var value = feature.m_Attribute[field.FieldName];
                            lineFeature.Attributes.Add(field.FieldName, value.ToString());
                        }

                        product.PointLayer.Add(lineFeature);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"读取文件失败：{shpFilePath}，错误：{ex.Message}");
                }
            }
        }

        private void ProcessProductShapefiles(string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                throw new DirectoryNotFoundException($"文件夹不存在：{folderPath}");
            }
            // 获取所有*Line.shp文件
            var lineShapefiles = Directory.GetFiles(folderPath, "PruductName.shp", SearchOption.AllDirectories);
            if (lineShapefiles.Length == 0)
            {
                throw new FileNotFoundException($"未找到PruductName.shp文件：{folderPath}");
            }

            foreach (var shpFilePath in lineShapefiles)
            {
                var product = new ProductLine()
                {
                    ProductName = Path.GetFileNameWithoutExtension(shpFilePath),
                    ProductLayer = new List<PointFeature>()
                };
                products.Add(product);
                try
                {
                    // 读取Shapefile文件
                    var sr = new ShapeDataGetterField(shpFilePath);

                    // 遍历每个要素（线）
                    foreach (var feature in sr.AllRecords)
                    {
                        if (feature.Point == null) continue;
                        var lineFeature = new PointFeature
                        {
                            Point = new Coordinate() { X = feature.Point.X, Y = feature.Point.Y },
                            Attributes = new Dictionary<string, object>()
                        };

                        // 读取属性数据
                        foreach (var field in sr.Columns)
                        {
                            var value = feature.m_Attribute[field.FieldName];
                            lineFeature.Attributes.Add(field.FieldName, value.ToString());
                        }

                        product.ProductLayer.Add(lineFeature);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"读取文件失败：{shpFilePath}，错误：{ex.Message}");
                }
            }
        }

        private void Export()
        {
            ScaleToWidth(products);

            agCIMProducts.FromProducts(products);

            agCIMProducts.CreateCellLines(GlobalBoundingBox);

            // 导出为JSON
            var json = JsonConvert.SerializeObject(products);
            
            File.WriteAllText(Path.Combine(m_outputJsonDir,"minExport.json"), json, System.Text.Encoding.UTF8);

            var json2 = JsonConvert.SerializeObject(agCIMProducts);
            json2 = json2.ReplaceAll(new string[] { ",\"symbol\":null" }, "");
            File.WriteAllText(m_outputJsonDir + "\\" + "EchartJSON.json", json2, System.Text.Encoding.UTF8);
        }
        private void ScaleToWidth(List<ProductLine> products)
        {
            var dx = 5000 / GlobalBoundingBox.Width;
            for (var i = 0; i < products.Count; i++)
            {
                var product = products[i];
                product.ScaleToWidth(dx, GlobalBoundingBox.MinX, GlobalBoundingBox.MaxY);
            }
        }
    }
}
